﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using Telerik.Web.UI;
using KPIS.Utils;
using System.Web.UI.HtmlControls;
using KPIS.GERP.GHRMS.MODEL;
using System.Collections;
using System.Globalization;
using KPIS.GERP.GHRMS.APP.Classes;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PR_SalaryPromoteCmdDtls : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private IEmployeeTypeBLL empTypeBLL = new EmployeeTypeBLL();
        private IPositionTypeBLL posTypeBLL = new PositionTypeBLL();
        private SystemYearTypeBLL yearTypeBLL = new SystemYearTypeBLL();
        private AppraisalsBLL appraisalsBLL = new AppraisalsBLL();
        private SalaryPromotionConfigBLL promotionManageBLL = new SalaryPromotionConfigBLL();
       // Command_BLL cmdBLL = new Command_BLL();
        //Command_BLL cmdBLL = new Command_BLL();
        private ICommandDetailBLL dcmdBLL = new CommandDetailBLL();
        private ICommandBLL cmdBLL = new CommandBLL();
        Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            IncludeJava();

            if (!IsPostBack)
            {
                lblID.Text = Request.QueryString["id"];
                bindEmpType();
                ListYear();
            }
            
        }
        public void IncludeJava()
        {
            HtmlGenericControl script = new HtmlGenericControl();
            script.TagName = "script";
            script.Attributes.Add("type", "text/javascript");
            script.Attributes.Add("src", "../../Scripts/jsfunction.js");
            Page.Header.Controls.Add(script);
        }
        private void bindEmpType()
        {
            IList<EmployeeTypeInfo> infoList = empTypeBLL.ListEmployeeTypes();
            ddlEmployeeType.DataSource = infoList;
            ddlEmployeeType.DataBind();
        }

        public void ListYear()
        {
            DataTable dt = new DataTable();
            DataColumn dc = dt.Columns.Add("Name");
            int myYearNow = DateTime.Today.Year + 543;

            for (int i = myYearNow - 10; i <= myYearNow + 10; i++)
            {
                dt.Rows.Add(Convert.ToString(i));
            }
            ddlYear.DataSource = dt;
            ddlYear.DataBind();
        }

        protected void ddlEmployeeType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            try
            {
                Session["id"] = lblID.Text + "|" + ddlEmployeeType.SelectedValue;

                DataSet ds = yearTypeBLL.GetYearType(int.Parse(ddlEmployeeType.SelectedValue));
                lblTypeYear.Text = ds.Tables[0].Rows[0]["year_type_name"].ToString();                
            }
            catch
            {
                lblTypeYear.Text = "";
            }
            rdoAppraisal.Items.Clear();
            lblMsg.Visible = false;
        }

        protected void ddlYear_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            rdoAppraisal.DataSource = appraisalsBLL.GetAppraisalsAround(int.Parse(ddlYear.SelectedValue));
            rdoAppraisal.DataBind();
            if (rdoAppraisal.Items.Count != 0)
            {
                lblMsg.Visible = false;
                rdoAppraisal.Items[0].Selected = true;
            }
            else
                lblMsg.Visible = true;
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            if (rdoAppraisal.Items.Count > 0)
            {
                LoadDataGridCheckBox();
                LoadDataGridCondition();
            }
            else 
            {
                lblMsg.Visible = true;
            }
           
        }

        public void cb1_Checked(object sender, EventArgs e)
        {
            CheckBox cb1 = (CheckBox)sender;
            CheckBox cb2;
            foreach (GridItem item in this.RadGrid2.Items)
            {
                cb2 = (CheckBox)item.Cells[0].FindControl("cb2");
                cb2.Checked = cb1.Checked;
            }
        }

       
        private void LoadDataGridCheckBox()
        {
            try
            {
                RadGrid2.DataSource = promotionManageBLL.select(int.Parse(ddlYear.SelectedValue), int.Parse(rdoAppraisal.SelectedValue), int.Parse(ddlEmployeeType.SelectedValue));
                RadGrid2.DataBind();
            }
            catch (Exception ex)
            {
                RadGrid2.DataSource = null;
                RadGrid2.DataBind();
            }
        }

        protected void RadGrid2_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            LoadDataGridCheckBox();
        }
        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }


        private void LoadDataGridCondition()
        {
            try
            {
                DataSet ds = posTypeBLL.ListPosionTypeClass(int.Parse(ddlEmployeeType.SelectedValue));
                RadGrid3.DataSource = ds.Tables[0];
                RadGrid3.DataBind();
            }
            catch (Exception ex)
            {
                RadGrid3.DataSource = null;
                RadGrid3.DataBind();
            }
        }

        protected void RadGrid3_ItemDataBound(object sender, GridItemEventArgs e)
        {

        }
        protected void RadGrid3_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "ExpandCollapse")
                return;
            LoadDataGridCondition();
        }


        private string filterJobSite()
        {
            CheckBox cb2;
            ArrayList arr = new ArrayList();
            foreach (GridItem item in this.RadGrid2.Items)
            {
                cb2 = (CheckBox)item.Cells[2].FindControl("cb2");
                if (cb2.Checked == true)
                {
                    arr.Add(item.OwnerTableView.DataKeyValues[item.ItemIndex]["pm_job_site_seq"].ToString());
                }

            }
            string[] strArray = arr.ToArray(typeof(string)) as string[];
            string str = string.Join(",", strArray);
            return str.Trim();
        }


        private string filterClass()
        {
            CheckBox cb2;
            ArrayList arr = new ArrayList();
            foreach (GridItem item in this.RadGrid3.Items)
            {
               // string ss = item.Cells[3].ToString();
                cb2 = (CheckBox)item.Cells[2].FindControl("cbClass");
                if (cb2.Checked == true)
                {
                    arr.Add(item.OwnerTableView.DataKeyValues[item.ItemIndex]["class_seq"].ToString());
                }

            }
            string[] strArray = arr.ToArray(typeof(string)) as string[];
            string str = string.Join(",", strArray);
            return str.Trim();
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            if (filterJobSite() == "" || filterClass() == "")
            {
                main.MessageAlert(this.Page, "กรุณาระบุเงื่อนไข!!");
                return;
            }
            bindCompare();
        }

        protected void RadGrid4_ItemCommand(object source, GridCommandEventArgs e)
        {
            RadGrid4.DataSource = (DataTable)Session["dtForSave"];
            RadGrid4.DataBind();
        }

        protected void RadGrid4_ItemDataBound(object sender, GridItemEventArgs e)
        {
            //duplicated
            if (e.Item.ItemType == GridItemType.Item || e.Item.ItemType == GridItemType.AlternatingItem)
            {
                CheckBox cb4;
                if (e.Item.Cells[3].Text == "Y")
                {
                    GridDataItem item = (GridDataItem)e.Item;  
                    cb4 = (CheckBox)item.Cells[2].FindControl("cb4");
                    cb4.Checked = true;
                    cb4.Enabled = false;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            CheckBox cb4;
            ArrayList arr = new ArrayList();
            int countGrdIsCheck = 0;
            foreach (GridItem item in this.RadGrid4.Items)
            {
                cb4 = (CheckBox)item.Cells[2].FindControl("cb4");
                if (cb4.Checked == true && cb4.Enabled == true)
                {
                    arr.Add(item.OwnerTableView.DataKeyValues[item.ItemIndex]["Sequence"].ToString());
                    countGrdIsCheck++;
                    cb4.Enabled = false;
                }

            }

            DataTable dt = (DataTable)Session["dtForSave"];
            for (int i = 0; i < countGrdIsCheck; i++)
            {
                DataRow dr;
                dr = dt.Select("Sequence =" + arr[i])[0];
                dcmdBLL.Insert(int.Parse(lblID.Text)
                    , int.Parse(dr["sequence"].ToString())
                    , (DateTime?)null
                    , dr["t_pos_seq"].ToString() != "" ? int.Parse(dr["t_pos_seq"].ToString()) : (int?)null
                    , dr["pos_ref"].ToString()
                    , dr["pos_name"].ToString()
                    , dr["t_class_seq"].ToString() != "" ? int.Parse(dr["t_class_seq"].ToString()) : (int?)null
                    , dr["working_job_site_seq"].ToString() != "" ? int.Parse(dr["working_job_site_seq"].ToString()) : (int?)null
                    , dr["job_site_name"].ToString()
                    , dr["t_new_salary"].ToString() != "" ? Double.Parse(dr["t_new_salary"].ToString()) : (Double?)null
                    , dr["salary"].ToString() != "" ? Double.Parse(dr["salary"].ToString()) : (Double?)null
                    , dr["sal_base"].ToString() != "" ? Double.Parse(dr["sal_base"].ToString()) : (Double?)null
                    , dr["percen_promote"].ToString() != "" ? Double.Parse(dr["percen_promote"].ToString()) : (Double?)null
                    , dr["amount"].ToString() != "" ? Double.Parse(dr["amount"].ToString()) : (Double?)null
                    , ""
                    , ssMng.EmpSeqI);
            }
            RadTabStrip1.SelectedIndex = 2;
            RadMultiPage1.SelectedIndex = 2;
            bindDataPrint();
        }


        private void bindCompare()
        {
            RadTabStrip1.SelectedIndex = 1;
            RadMultiPage1.SelectedIndex = 1;

            DataSet ds = new DataSet();

            DataTable dt = promotionManageBLL.select(filterJobSite(), filterClass());
            ds = dcmdBLL.LoadCommandDetails((int?)null, Convert.ToInt32(lblID.Text), (int?)null);
            DataTable dt2 =  ds.Tables[0];
            dt.Columns.Add("duplicated", typeof(string));

            foreach (DataRow dr in dt.Rows)
            {
                foreach (DataRow dr2 in dt2.Rows)
                {
                    if (dr["emp_seq"].ToString() == dr2["emp_seq"].ToString())
                    {
                        dr["duplicated"] = "Y";
                        break;
                    }
                    else
                        dr["duplicated"] = "N";
                }
            }

            dt.AcceptChanges();
            Session["dtForSave"] = dt;

            RadGrid4.DataSource = dt;
            RadGrid4.DataBind();
            if (dt.Rows.Count != 0)
                btnSave.Visible = true;
            else
                btnSave.Visible = false;

            bindDataPrint();
        }
        private void bindDataPrint()
        {
            DataSet ds = new DataSet();
            DataSet ds2 = new DataSet();
            DataTable dt = new DataTable();
            DataTable dt2 = new DataTable();
            ds = dcmdBLL.LoadCommandDetails((int?)null, Convert.ToInt32(lblID.Text), (int?)null);
            dt = ds.Tables[0];

            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();

            ds2 = cmdBLL.LoadCommands(SystemInfo._CmdEmployee, Convert.ToInt32(lblID.Text), (int?)null, (int?)null);
            dt2 = ds2.Tables[0];
            if (dt2.Rows.Count > 0)
            {
                lblCmdName.Text = dt2.Rows[0]["cmd_name"].ToString();
                lblRefNo.Text = dt2.Rows[0]["cmd_ref_no"].ToString();
                lblAppDate.Text = string.Format("{0:dd/MM/yyyy}", dt2.Rows[0]["approved_date"]);
            }
        }

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int seq = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"]);
                dcmdBLL.Delete(seq, ssMng.EmpSeqI);
            }
            if (e.CommandName == "btnClick")
            {
                return;
            }
            bindCompare();
        }

        protected void RadTabStrip1_TabClick(object sender, RadTabStripEventArgs e)
        {
            int nIndex = RadTabStrip1.SelectedIndex;
            switch (nIndex)
            {
                case 0:
                    //txtDate.Value = ((DateTime)date).ToShortDateString();
                    break;
                case 1:
                    bindCompare();
                    break;
                case 2:
                    bindDataPrint();
                    break;
                default:
                    //txtDate.Value = date.ToString();
                    break;
            }
        }


        

    }
}
